﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DatabaseComponent;

public partial class CoursesViewEN : System.Web.UI.Page
{

    public List<Courses> lstGridCourses
    {
        get
        {
            if (ViewState["lstGridCourses"] == null)
            {
                ViewState["lstGridCourses"] = System.Guid.NewGuid().ToString();
            }


            if (Session[ViewState["lstGridCourses"].ToString()] == null)
            {
                Session[ViewState["lstGridCourses"].ToString()] = new List<Courses>();

            }

            return (List<Courses>)Session[ViewState["lstGridCourses"].ToString()];

        }
        set
        {
            if (ViewState["lstGridCourses"] == null)
            {
                ViewState["lstGridCourses"] = System.Guid.NewGuid().ToString();
            }

            Session[ViewState["lstGridCourses"].ToString()] = value;
        }



    }


    protected void Page_Load(object sender, EventArgs e)
    {



        Persons objPersons = GlobalVars.getCurrentPerson();
        checkSecurityAndCustomizePage(objPersons);

        if (!Page.IsPostBack)
        {
            bindChecked();
            bindGrid("");
        }

    }

    /// <summary>
    /// this function will get the checked box value from database
    /// </summary>
    private void bindChecked()
    {
        SystemOptionsDB objSystemOptionsDB = new SystemOptionsDB(ConnectionStrings.LMS);
        List<SystemOptions> lstOptions = objSystemOptionsDB.Select("", "");
        
        if (lstOptions.Count > 0)
            chkShowLanguageColumn.Checked = lstOptions[0].ShowCourseLanguage;
        else
            chkShowLanguageColumn.Checked = true;


        if (lstOptions.Count > 1)
            chkShowTime.Checked = lstOptions[1].ShowCourseLanguage;
        else
            chkShowTime.Checked = true;

    }

    protected void chkShowLanguageColumn_CheckedChanged(object sender, EventArgs e)
    {
        SystemOptionsDB objSystemOptionsDB = new SystemOptionsDB(ConnectionStrings.LMS);
        List<SystemOptions> lstOptions = objSystemOptionsDB.Select("", "");
        if (lstOptions.Count < 2)
        {



            SystemOptions so = null;

            if (lstOptions.Count == 0)
            {
                so = new SystemOptions();
                so.ShowCourseLanguage = chkShowLanguageColumn.Checked;


                objSystemOptionsDB.Insert(so);
            }

            if (lstOptions.Count == 1)
            {

                so = new SystemOptions();
                so.ShowCourseLanguage = chkShowTime.Checked;
                objSystemOptionsDB.Insert(so);
            }

            lstOptions = objSystemOptionsDB.Select("", "");


            if (lstOptions.Count < 2)
                return;
        }


        lstOptions[0].ShowCourseLanguage = chkShowLanguageColumn.Checked;


        objSystemOptionsDB.Update(lstOptions[0]);

        lstOptions[1].ShowCourseLanguage = chkShowTime.Checked;

        objSystemOptionsDB.Update(lstOptions[1]);

    }



    /// <summary>
    /// this function will bind the grid 
    /// </summary>
    protected void bindGrid(string strIn)
    {

        List<Courses> lstCourses = search(strIn);



        lstGridCourses = new List<Courses>(from obj in lstCourses orderby obj.CourseNameEN select obj);

        grdUsers.DataSource = lstCourses;
        grdUsers.DataBind();
    }



    /// <summary>
    /// it will check the security and customize the page
    /// </summary>
    /// <param name="currentPerson">the person to set security to his previleges</param>
    protected void checkSecurityAndCustomizePage(Persons currentPerson)
    {
        //Security Check

        if (!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Courses_page))
            Response.Redirect("LoginEN.aspx");








    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {

        bindGrid(txtSearch.Text);

    }

    /// <summary>
    /// this function will search in folders and return the values
    /// </summary>
    /// <param name="txtText">the text to search for</param>
    /// <returns>a list of Courses matched</returns>
    protected List<Courses> search(string txtText)
    {
        CoursesDB objCoursesDB = new CoursesDB(ConnectionStrings.LMS);
        List<Courses> lstRet = new List<Courses>();
        if (txtText.Trim() == "")
        {
            List<Courses> lstNew = objCoursesDB.Select("", " order by [CourseNameEN] ");
            //lstNew = new List<Courses>(from objFol in lstNew where objFol.StatusID != 2 select objFol);
            return lstNew;
        }

        string[] strValues = null;
        if (txtText.Trim()[0] == '\"' && txtText.Trim()[txtText.Trim().Length - 1] == '\"')
        {
            try
            {
                strValues = new string[] { txtText.Trim().Substring(1, txtText.Trim().Length - 2) };
                if (strValues[0] == "")
                    strValues = new string[0];
            }
            catch
            {
                strValues = new string[0];
            }
        }
        else
        {
            strValues = txtText.Trim().Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
        }

        foreach (string strValue in strValues)
        {
            Courses objCourses = new Courses();
            objCourses.CourseNameAR = objCourses.CourseNameEN = objCourses.TargetAR = objCourses.TargetEN = objCourses.OutlineAR = objCourses.OutlineEN = "%" + strValue + "%";
            List<Courses> lstCourses = objCoursesDB.SearchOrLike(objCourses);
            //lstCourses = new List<Courses>(from objFol in lstCourses where objFol.StatusID != 2 select objFol);

            foreach (Courses objFol in lstCourses)
            {
                if ((from objIn in lstRet where objIn.ID == objFol.ID select objIn).ToList().Count == 0)
                {
                    lstRet.Add(objFol);
                }
            }

        }


        return lstRet;



    }





    protected void grdUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

        Persons objCurrentPersons = GlobalVars.getCurrentPerson();
        checkSecurityAndCustomizePage(objCurrentPersons);



        //security
        if (!objCurrentPersons.lstAllRulesIDs.Contains((long)RulesEnum.Editing_courses_page))
        {
            lblError.Text = "Security error , you can view only";
            lblResult.Text = "";

            return;
        }


        long CoursesID = long.Parse(grdUsers.DataKeys[e.RowIndex]["ID"].ToString());



        CoursesDB objCoursesDB = new CoursesDB(ConnectionStrings.LMS);
        List<Courses> lstCourses = objCoursesDB.getCoursesByID(CoursesID);




        if (lstCourses.Count == 0)
        {
            lblError.Text = "No Courses to delete";
            lblResult.Text = "";
            return;
        }






        bool bRet = objCoursesDB.deleteAll(lstCourses[0]);
        if (bRet)
        {
            lblResult.Text = "Deleted ok.";
            bindGrid(txtSearch.Text);
        }
        else
        {
            lblError.Text = "Error Deleting.";
        }












    }

    protected void btnNew_Click(object sender, EventArgs e)
    {
        Response.Redirect("CoursesEN.aspx");
    }
    protected void grdUsers_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdUsers.DataSource = lstGridCourses;
        grdUsers.PageIndex = e.NewPageIndex;

        grdUsers.DataBind();
    }
}
